import { Component, OnInit } from '@angular/core';
import { sellCouponbagManageService } from './sell-couponbag-manage.service'
import { DatePipe } from '@angular/common';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Router, ActivatedRoute, NavigationExtras} from '@angular/router';
import { differenceInCalendarDays, setHours } from 'date-fns';
import { DisabledTimeFn, DisabledTimePartial } from 'ng-zorro-antd/date-picker';
import { CommonService } from '../../../services-common/common.service';
import { PermissionService } from '../../../service/permission.service';

@Component({
  selector: 'app-sell-couponbag-manage',
  templateUrl: './sell-couponbag-manage.component.html',
  styleUrls: ['./sell-couponbag-manage.component.scss'],
  providers: [DatePipe]
})
export class SellCouponbagManageComponent implements OnInit {

  range(start: number, end: number): number[] {
    const result: number[] = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  }
  disabledDate = (current: Date): boolean =>
    // Can not select days before today and today
    differenceInCalendarDays(current, new Date()) < 0;


  searchOptions = [
    { type: 1, labelText: '名称', valueKey: 'name', value: '' },
    {
      type: 2,
      labelText: '状态',
      valueKey: 'state',
      value: [],
      multiple: false,
      notTostr: false,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [
        {value: 0, label: '启用'},
        {value: 1, label: '禁用'}
      ],
    }
  ];
  seachForms: any = {}

  // table
  tableForms: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };
  // 表格data
  tableData: any = [];

  /**
   * 手动发放优惠券包 Modal
   * ----------------------------------------------------------------
   */
  isVisible: boolean = false;
  modelLoading: boolean = false;
  activeId: any = '';
  userIdList: any = ''; // 用户ID

  /**
   * 增发兑换码 Modal
   * ----------------------------------------------------------------
   */
  changeCodeVisible = false;
  subChangeCodeLoading = false;
  changeCodeForm!: FormGroup;

  constructor(
    private datePipe: DatePipe,
    private message: NzMessageService,
    private router: Router,
    private service: sellCouponbagManageService,
    public permission: PermissionService,
    private commonService: CommonService,
    private fb: FormBuilder
  ) { }

  ngOnInit(): void {
    this.changeCodeForm = this.fb.group({
      packageId: [''],
      num: [null, [Validators.required]],
      expireTime: [null, [Validators.required]]
    });

    this.loadTable();
  }

  // loadTable
  async loadTable() {
    let params = {
      ...this.seachForms,
      page: this.tableForms.page,
      pageSize: this.tableForms.pageSize
    }

    this.tableForms.tableLoading = true;
    const res: any = await this.service.couponBagTableData(params);
    this.tableForms.tableLoading = false;

    if (res.code === 0) {
      const { records, total } = res.data;
      this.tableData = records || [];
      this.tableForms.total = total || 0;
    } else {
      this.message.error(res.message);
    }
  }

  queryResetData(params: any) {
    this.seachForms = params;
    this.tableForms.page = 1;
    this.loadTable();
  }

  /**
   * 页面跳转
   * @param num 0：新增,1：编辑,2：查看,3：复制
   * @param item 单项data
   */
  jumpPage(num: number, item?: any) {
    this.router.navigate(['/sell/couponbagHandle'], {
      queryParams: {
        id: num == 0 ? '' : item.id,
        mode: num
      }
    })
  }

  // 确认删除
  async deleteConfirm(id: any) {
    let params = {
      id: id,
      deleteState: 1
    }
    const res: any = await this.service.editCouponData(params);
    if (res.code === 0) {
      this.message.success('删除成功');
      this.loadTable();
    } else {
      this.message.error(res.message);
    }
  }

  // model确定
  async handleOk() {
    if (!this.userIdList) {
      this.message.warning('请输入用户ID');
      return
    }
    let params = {
      id: this.activeId,
      userIdList: this.userIdList
    }

    this.modelLoading = true;
    const res: any = await this.service.nanualReleaseData(params);
    this.modelLoading = false;

    if (res.code === 0) {
      this.message.success('手动发放成功');
      this.isVisible = false;
      this.tableData();
    } else {
      this.message.error(res.message);
    }
  }
  // model取消
  handleCancel(): void {
    this.isVisible = false;
  }
  // 关闭模态框
  closeModel(event: any) {
    this.userIdList = '';
    this.modelLoading = false;
  }

  // 手动发放卡包(model弹出)
  manualModel(id: any) {
    this.activeId = id;
    this.isVisible = true;
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableForms.page = index;
    this.loadTable()
  }
  // 页数改变时回调
  onPageSizeChange(sizeNum: number) {
    this.tableForms.page = 1;
    this.tableForms.pageSize = sizeNum;

    this.loadTable()
  }

  /**
   * ----------------------------------------------------------------
   * 增发兑换码 Modal
   * ----------------------------------------------------------------
   */
  overTimeChange(result: Date) {
    let ndate = result ? this.datePipe.transform(result, 'yyyy-MM-dd HH:mm:ss') : '';
    this.changeCodeForm.value.expireTime = ndate;
  }

  showSendCodeModal(item: any) {
    this.changeCodeForm.reset();
    this.changeCodeForm.get('packageId')?.setValue(item.id);
    this.changeCodeVisible = true;
  }

  async subAddIssue() {
    if (this.changeCodeForm.valid) {
      let params = {
        ...this.changeCodeForm.value
      }
      this.subChangeCodeLoading = true;
      const res: any = await this.service.addChangeCodeData(params);
      this.subChangeCodeLoading = false;

      if (res.type === 'application/octet-stream') {
        this.changeCodeVisible = false;
        this.message.success('已成功增发兑换码');
        this.loadTable();
        this.commonService.downLoadBlobFile(res, '兑换码记录');
      } else {
        this.message.error('操作失败');
      }
    } else {
      Object.values(this.changeCodeForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }
}
